package day15.OneStageSystem;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class CardServer {
    static Map<String,Socket> map = new HashMap<>();
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(9999);
        System.out.println("服务端启动成功!");
        while (true){
            Socket client = server.accept();
            new ServerThread(client).start();
        }
    }
}
class ServerThread extends Thread{
    Scanner sc = new Scanner(System.in);
    Socket client;
    public ServerThread(Socket client){
        this.client = client;
    }

    public void run() {
        try(
            BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()))
        ){
            String from = br.readLine();
            System.out.println(from+"发来消息");
            //存储客户
            CardServer.map.put(from,client);
            //读取数据
            new Thread(()->{
                while (true){
                    try {
                        String msg = br.readLine();
                        if (msg!=null) System.out.println(msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            while (true){
                System.out.println("请输入需要发送消息的用户电话号码:");
                String phone = sc.next();
                boolean b = false;
                for (String key:CardServer.map.keySet()){
                    if (key.equals(phone)){
                        System.out.println("请输入发送的消息:");
                        String msg = sc.next();
                        //给对方发送消息
                        OutputStream os = CardServer.map.get(phone).getOutputStream();
                        os.write(("客服:"+msg+"\n").getBytes());
                        b = true;
                    }
                }
                if (!b){
                    System.out.println("该用户不存在");
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
 class CardThread extends Thread{
    Socket clint;
    volatile boolean b;
    public CardThread(Socket clint){
        this.clint = clint;
    }

    public void run() {
        try(
            BufferedReader br = new BufferedReader(new InputStreamReader(clint.getInputStream()))
        ){
            while (!b){
                String msg = br.readLine();
                if (msg!=null&&!msg.equals("")){
                    System.out.println(msg);
                }
            }
        }catch (Exception e){

        }
    }
}